package cn.btks.commonserver.util;


import java.util.List;

/**
 * Created by zhangjing on 2019/4/28.
 */
public class ListUtil {

    /**
     * 利用subList方法进行分页
     *
     * @param list       分页数据
     * @param pageSize   每页显示行数
     * @param pageNumber 当前页面
     */
    public static List<?> pageBySubList1(List list, int pageNumber, int pageSize) {
        int totalcount = list.size();
        int pagecount = 0;
        List<?> subList;
        int m = totalcount % pageSize;
        if (m > 0) {
            pagecount = totalcount / pageSize + 1;
        } else {
            pagecount = totalcount / pageSize;
        }
        if (m == 0) {
            subList = list.subList((pageNumber - 1) * pageSize, pageSize * (pageNumber));
        } else {
            if (pageNumber == pagecount) {
                subList = list.subList((pageNumber - 1) * pageSize, totalcount);
            } else {
                subList = list.subList((pageNumber - 1) * pageSize, pageSize * (pageNumber));
            }
        }
        return subList;
    }

    /**
     * 开始分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List<?> pageBySubList(List list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        //确认所选页大于实际页数
        if (pageNum > pageCount) {
            return null;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }
}


